package com.idp.web.controller;

import com.idp.common.base.BaseController;
import com.idp.common.base.BaseResult;
import com.idp.common.constants.CommonConstants;
import com.idp.common.util.ValidateUtils;
import com.idp.web.dto.DepartmentSelectListDTO;
import com.idp.web.dto.DepartmentTreeDTO;
import com.idp.web.entity.Department;
import com.idp.web.entity.HospitalDepartment;
import com.idp.web.service.IDepartmentService;
import com.idp.web.service.IHospitalDepartmentService;
import com.idp.web.vo.DepartmentSearchVo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 医院科室controller
 *
 * @author xubinren
 * @version 1.0
 * @date 2018/3/2
 */
@Controller
@RequestMapping("/hospitalDepartment")
public class HospitalDepartmentController extends BaseController {

    private Logger logger = Logger.getLogger(HospitalDepartmentController.class);

    @Resource
    private IHospitalDepartmentService hospitalDepartmentService;

    @Resource
    private IDepartmentService departmentService;

    /**
     * 初始化查询页面
     *
     * @return
     */
    @RequestMapping("/init")
    public String init() {
        return "hospital/department/departmentSearch";
    }

    /**
     * 初始化查询页面
     *
     * @return
     */
    @RequestMapping("/templateInit")
    public String templateInit() {
        return "hospital/template/departmentSearch";
    }

    /**
     * 查询当前医院的科室列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/list")
    public String list(DepartmentSearchVo departmentSearchVo, HttpServletRequest request) {
        try {
            departmentSearchVo.setParentId("0");
            departmentSearchVo.setHospitalId(getUserId());
            //列表信息
            request.setAttribute("departmentList", departmentService.findForTreeTable(departmentSearchVo));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        if (CommonConstants.HOSPITAL_TEMPLATE_PAGETYPE.equals(departmentSearchVo.getPageType())){
            return "hospital/template/departmentList";
        }
        return "hospital/department/departmentList";
    }

    /**
     * 添加编辑医院的科室页面初始化
     *
     * @param request HttpServletRequest
     * @return String
     */
    @RequestMapping("/templateDepartmentList")
    public String templateDepartmentList(HttpServletRequest request) {
        try {
            String hospitalId = CommonConstants.STRING_BLANK;
            if (CommonConstants.USER_TYPE_HOSPITAL == getUserType()){
                hospitalId = getUserId();
            }
            List<DepartmentSelectListDTO> listWeightOne = departmentService.selectListByWeight(CommonConstants.DEPARTMENT_WEIGHT_ONE,hospitalId);
            List<DepartmentSelectListDTO> listWeightTwo = departmentService.selectListByWeight(CommonConstants.DEPARTMENT_WEIGHT_TWO,hospitalId);
            request.setAttribute("listWeightOne", listWeightOne);
            request.setAttribute("listWeightTwo", listWeightTwo);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "hospital/template/departmentList";
    }

    /**
     * 查询下级科室
     * @return String
     */
    @RequestMapping("/treeTable")
    @ResponseBody
    public String treeTable(DepartmentSearchVo departmentSearchVo){
        JSONArray json = new JSONArray();
        try {
            departmentSearchVo.setHospitalId(getUserId());
            json.addAll(departmentService.findForTreeTable(departmentSearchVo));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return json.toString();
    }

    /**
     * 获取科室树状结构
     *
     * @return String
     */
    @RequestMapping("/getDepartmentForTree")
    @ResponseBody
    public String getDepartmentForTree(Long currentId){
        JSONArray json = new JSONArray();

        DepartmentSearchVo departmentSearchVo = new DepartmentSearchVo();
        if (getCurrentUser().getUserType() == CommonConstants.USER_TYPE_HOSPITAL){
            departmentSearchVo.setHospitalId(getUserId());
        }
        List<DepartmentTreeDTO> departmentTreeList = departmentService.find(departmentSearchVo);

        if(departmentTreeList != null && departmentTreeList.size() > 0){
            for(DepartmentTreeDTO departmentTreeDTO : departmentTreeList){
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", departmentTreeDTO.getId());
                map.put("name", departmentTreeDTO.getDepartmentName());
                map.put("pId", departmentTreeDTO.getParentId());
                json.add(map);
            }
        }

        return json.toString();
    }

    /**
     * 新增修改页面初始化
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/hospitalDepartment")
    public String hospitalDepartment(String id, HttpServletRequest request) {
        try {
            if (ValidateUtils.isNotEmpty(id)) {
                Department department = departmentService.getById(id);
                request.setAttribute("department", department);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "hospital/department/department";
    }

    /**
     * 添加编辑医院的科室页面初始化
     *
     * @param id      医院id
     * @param request HttpServletRequest
     * @return String
     */
    @RequestMapping("/hospitalsDepartment")
    public String hospitalsDepartment(String id, HttpServletRequest request) {

        // 科室树信息
        List<String> menuIds = hospitalDepartmentService.selectDepartmentIds(getUserId());

        JSONArray json = new JSONArray();
        List<DepartmentTreeDTO> departmentTreeList = departmentService.find(new DepartmentSearchVo());
        if(departmentTreeList != null && departmentTreeList.size() > 0){
            for(DepartmentTreeDTO menu : departmentTreeList){
                Map<String, Object> map = new HashMap<String,Object>();
                map.put("id", menu.getId());
                map.put("name", menu.getDepartmentName());
                map.put("pId", menu.getParentId());

                // 选中角色拥有的菜单权限
                if(menuIds != null && menuIds.contains(menu.getId())){
                    map.put("checked", true);
                }
                else{
                    map.put("checked", false);
                }

                json.add(map);
            }
        }
        request.setAttribute("menuList", json.toString());
        return "hospital/department/hospitalsDepartment";
    }

    /**
     * 保存
     *
     * @param department 科室信息
     * @return String
     */
    @RequestMapping("/save")
    @ResponseBody
    public String save(Department department,HospitalDepartment hospitalDepartment, HttpServletRequest request) {
        JSONObject json = new JSONObject();
        boolean saveCheck = false;
        try {
            // 修改
            if (ValidateUtils.isNotEmpty(department.getId())) {
                saveCheck = departmentService.update(department,getUserId());
            }
            // 新增
            else {
                saveCheck = departmentService.add(department,hospitalDepartment,getUserId());
            }
            if (saveCheck){
                json.put("result", "save_success");
            }else {
                json.put("result", "save_fail");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("result", "save_fail");
        }
        return json.toString();
    }

    /**
     * 保存医院下科室信息
     *
     * @param menuIds 科室ids
     * @return String
     */
    @RequestMapping("/saveHospitalDepartment")
    @ResponseBody
    public String saveHospitalDepartment(String menuIds) {
        JSONObject json = new JSONObject();
        boolean saveCheck = false;
        try {
            if (StringUtils.isNotEmpty(menuIds) && !CommonConstants.STRING_COMMA.equals(menuIds.trim())){
                saveCheck = hospitalDepartmentService.saveOrUpdate(getUserId(),menuIds,getUserId());
            }

            if (saveCheck){
                json.put("result", "save_success");
            }else {
                json.put("result", "save_fail");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("result", "save_fail");
        }
        return json.toString();
    }

    /**
     * 删除
     *
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(String departmentId) {
        JSONObject json = new JSONObject();
        try {
            hospitalDepartmentService.deleteBy(getUserId(),departmentId);
            json.put("result", "delete_success");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("result", "delete_fail");
        }

        return json.toString();
    }

    /**
     * 查询科室的统计信息
     *
     * @return BaseResult
     */
    @RequestMapping("/queryStatistics")
    @ResponseBody
    public BaseResult queryStatistics() {
        JSONObject json = new JSONObject();
        //一级科室
        json.put("departmentWeightOne", departmentService.queryStatistics(CommonConstants.DEPARTMENT_WEIGHT_ONE,getUserId()));
        //二级科室科室
        json.put("departmentWeightTwo", departmentService.queryStatistics(CommonConstants.DEPARTMENT_WEIGHT_TWO,getUserId()));
        return sendResult200(json);
    }
}
